<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\api\controller;

use think\Controller;
use think\Db;

class  Base extends Controller
{
    protected $_error;
    protected $_header;//用户的请求头信息
    public $otherLogin  = '您的账号已在其他设备登录';
    public $frost = '您的账号已被冻结';

    // 构造函数
    public function __construct()
    {
        // 如果配置项为空 则直接返回

    }

    /**
     * 获取教师身份是否审核通过一级提示
     * @param $user_id
     * @return array
     */
    protected function getUserStatusForSee($user_id)
    {
        $user = Db::table('up_u_user')
            ->where('user_id',$user_id)
            ->field('user_id,user_type,user_status')
            ->find();
        if($user['user_type'] == 2 && $user['user_status'] != 1){
            if($user['user_status'] == 6){
                return array('status' => 0, 'msg' => '请认证身份信息');
            }elseif ($user['user_status'] == 5){
                return array('status' => 0, 'msg' => '目前审核正在审核中，无法进行操作');
            }elseif ($user['user_status'] == 2){
                return array('status' => 0, 'msg' => '审核失败，需重新完善信息');
            }else{
                return array('status' => 0, 'msg' => '未知错误，请刷新重试');
            }
        }else{
            return array('status' => 200, 'msg' => 'OK');
        }
    }
    /**
     * 验证唯一——单点登录
     * user_id，time，salt，value
     * @return string
     * 111  ok
     * 110  账户冻结
     * 112  异地登录
     */
    public function checkAll($uid, $time, $value, $reqKey)
    {//
        if($uid == 0) {
            return 111;
        } else {
            $user = Db::table('up_u_user')->where('user_id',$uid)->find();
            if($user['user_status'] == 3){//冻结
                return 110;
            }
//            $user = Db::table('up_u_user')->where('user_id', $uid)->find();
            $token = $user['user_token'];
            $appId = "A6070308312682";
            $appkey = "9AF807B0-BE12-F521-6998-6D57B0CCE8BB";
            $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
            $myvalue = md5($uid . 'XW' . $token . 'XW' . $time);
            if($myvalue != $value || $myreqKey != $reqKey) {
                return 112;
            } else {
                Db::table('up_u_user')->where('user_id', $uid)->setField('user_f_online',1);
                //修改优惠券状态
                $time_coupon = date('Y-m-d H:i:s');
                //未过期、上架中的优惠券列表
                $coupon = Db::table('up_coupon')
//                    ->join('up_coupon', 'mc_coupon_id = coupon_id', 'left')
                    ->where('coupon_end', '<', $time_coupon)
                    ->where('coupon_status', 1)
//                    ->where('mc_status', 1)
                    ->where('coupon_online', 1)
                    ->field('coupon_id')
//                    ->where('mc_user_id', $uid)
                    ->select();
                if($coupon){
                    foreach($coupon as $k => $v) {
                        //修改优惠券状态
                        Db::table('up_coupon')->where('coupon_id', $v['coupon_id'])->setField('coupon_status', 2);
                        //修改我的优惠券状态
                        Db::table('up_my_coupon')
                            ->where('mc_status', 1)
                            ->where('mc_type', 1)
                            ->where('mc_coupon_id', $v['coupon_id'])
                            ->setField('mc_status', 3);
                    }
                }
                
                return 111;
            }
        }
    }
    

    /**
     * 云之讯发送短信
     * @param $phone
     * @param $num
     * @return mixed
     */
    public function duaxin($phone, $num)
    {
//        header("Content-type: text/html; charset=utf-8");
        $body_json = array(
            'sid' => '05b0c3cc6133227764acc0e1b6ea21ad',
            'token' => '42c56907ae16aa3615c3945e72e26249',
            'appid' => '414eed7c02e146598852492fa626204d',
            'templateid' => '400297',
            'param' => $num,
            'mobile' => $phone,
            'uid' => '',
        );
        $body = json_encode($body_json);
        $header = array(
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8',
        );
        $url = 'https://open.ucpaas.com/ol/sms/sendsms';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result, true);
        return $res;
    }
    public function rongyun($uid,$name,$imageurl){//echo 1;die;
        $appKey = 'm7ua80gbmoamm';
        $appSecret = 'xKkOU8czsBb';
        $uid = strval($uid);
        $body = "userId={$uid}&name={$name}&portraitUri={$imageurl}";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret.$nonce.$timeStamp);
        $header = array(
            'App-Key:'.$appKey,
            'Nonce:'.$nonce,
            'Timestamp:'.$timeStamp,
            'Signature:'.$sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/user/getToken.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
//    var_dump($res) ;
    }
    /***
     * @return bool
     * 签到
     */
    protected function signIn($user_id){
        extract(input());
        $where = array();
        $where['si_user_id'] = $user_id;
        $where['si_date'] = date('Y-m-d');
        $res = Db::table('up_sign_in')
            ->where($where)
            ->find();
        if($res){
            return true;
        }else{
            $where['si_time'] = date('Y-m-d H:i:s');
            $score = Db::table('up_sign_config')->where('id',1)->value('score');
            $last_day = Db::table('up_sign_in')
                ->where('si_user_id',$user_id)
                ->order('si_date DESC')
                ->find();
            //-----------------------------------
            $where['si_day'] = 1;
            $where['si_score'] = $score;
            //-----------------------------------
            $honor = true;
            if($last_day){
                $many = $this->diffBetweenTwoDays($last_day['si_date']);
                if($many == 1){
                    $where['si_day'] = $last_day['si_day']+1;
                    if($where['si_day'] >= 3){
                        $where['si_score'] = $score*3;
                        //连续达到7天第一次时，得到勋章---start---------------------
                        if($where['si_day'] == 7){
                            $honor = $this->getHonorForEvery ($user_id,3);
                        }
                        //连续达到7天第一次时，得到勋章--- end-----------------------
                    }else{
                        $where['si_score'] = $score*$where['si_day'];
                    }
                }
            }
            $res2 = Db::table('up_sign_in')->insert($where);
            if($res2){
                //得金币入流转start-----
                $this->goldInOut ($user_id,$where['si_score'],1,1);
                //得金币入流转end-------
                Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_integral',$where['si_score']);
                return $honor;
            }else{
                return false;
            }
        }

    }
    /***
     *
     * 单独处理各种达到勋章的处理（1关卡 2书籍 3签到 4被5位好友关注 5知识对战首胜 6知识5连胜 7知识10连胜 8班级周前三 9班级周第一 10购物）
     */
    protected function getHonorForEvery ($user_id,$num,$timer='')//Timer只是为了定时器的时候不返回数据了
    {
        $honor = Db::table('up_u_user')->where('user_id',$user_id)->value('user_honor');
        if($num == 10){//
            Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_use_couple',1);
        }
        if(!strstr($honor,",$num,")){
            $str = ",$num,";
            if($honor){
                $str = $honor . "$num,";
            }
            //1、改勋章
            $update = [
                'user_honor'=>$str
            ];
            if($num == 2){//如果是书籍，说明此人最少通过一本了，改一下状态
                $update['user_pass_one'] = 2;
            }
            Db::table('up_u_user')->where('user_id',$user_id)->update($update);
            //2、得金币
            $honor = Db::table('up_honor')->where('id',$num)->find();
            $exp = $honor['exp'];
            Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_integral',$exp);
            //得金币入流转start-----
            $this->goldInOut ($user_id,$exp,6,1);
            //得金币入流转end-------
            //3、得优惠券
            $couponID = $honor['coupon_id'];
            $cangive = $this->couponStatusNow($user_id,$couponID);
            //
            if(!$timer){
                $coupon_name = Db::table('up_coupon')->where('coupon_id',$couponID)->field('coupon_name,coupon_price,coupon_use')->find();
                $honor['coupon_name'] = $coupon_name['coupon_name'];
                $honor['coupon_price'] = $coupon_name['coupon_price'];
                $honor['coupon_use'] = $coupon_name['coupon_use'];
                if($cangive == false){
                    $honor['coupon_price'] = '';
                }
                return $honor;
            }else{
                return true;
            }

        }else{
//            if($num == 2){ //如果是书籍，说明此人最少通过一本了，改一下状态(因为有可能进不去上面的)
//                Db::table('up_u_user')->where('user_id',$user_id)->setField('user_pass_one',2);
//            }
            return false;
        }

    }
    /***
     *
     * 不管是勋章还是奖励，我该得的优惠券
     */
    protected function couponStatusNow ($user_id,$couponID)
    {
        if($couponID){
            $today = date('Y-m-d H:i:s');
            $coupon = Db::table('up_coupon')->where('coupon_id',$couponID)->field('coupon_end,coupon_status,coupon_online')->find();
            //优惠券有没有过期
            if($coupon['coupon_online'] != 1){
                $status = $coupon['coupon_online']+2;
            }else{
                if($coupon['coupon_end'] <= $today){
                    $status = 3;
                }else{
                    $status = 1;
                }
            }
            //可以加入的再加入
            if($coupon['coupon_online'] == 1 && $status == 1){
                $mycou = [
                    'mc_user_id'=>$user_id,
                    'mc_coupon_id'=>$couponID,
                    'mc_status'=>$status,
                    'mc_time'=>$today
                ];
                Db::table('up_my_coupon')->insert($mycou);
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    /***
     * @return bool
     * 获取两天之间的差
     */
    protected function diffBetweenTwoDays ($day2)
    {
        $day1 = date('Y-m-d');
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);
        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }
    /***
     * @return bool
     * 获取用户当前段位信息
     */
    protected function getUserExpLevel ($user_id)
    {
        $exp = Db::table('up_u_user')->where('user_id',$user_id)->value('user_exp');
        $level = Db::table('up_exp_level')
            ->where('el_min','<=',$exp)
            ->order('el_level DESC')
            ->find();
        return $level;
    }
    /***
     * @return bool
     * 单独给用户加经验加金币(为闯关和对战)
     * type：1时为闯关  2时为对战胜利方  3为对战失败方  4为每日挑战胜利
     */
    protected function addUserExp ($user_id,$exp,$score,$type,$coupon='')
    {
        $today = date('Y-m-d H:i:s');
        Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_exp',$exp);
        Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_exp_week',$exp);
        Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_exp_month',$exp);
        Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_exp_year',$exp);

        if($type != 3){
            //时间
            Db::table('up_u_user')->where('user_id',$user_id)->setField('user_exp_lasttime',$today);
            Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_integral',$score);
        }else{
            //此时说明我失败了，减积分清连胜
            Db::table('up_u_user')->where('user_id',$user_id)->setDec('user_integral',$score);
            //清连胜纪录
            Db::table('up_u_user')->where('user_id',$user_id)->setField('user_f_continu',0);
            //
            Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_f_all');
        }
        //闯关时直接给优惠券
        if($type == 1){
            if($coupon){
                $this->couponStatusNow($user_id,$coupon);
            }
        }
        //对战达到连胜要给优惠券的
        if($type == 2){
            Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_f_continu');
            Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_f_all');
            Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_f_win');
            $con = Db::table('up_u_user')->where('user_id',$user_id)->value('user_f_continu');
            if($con >= 2 && $con <= 6){
                $coupon = Db::table('up_fight_continue_coupon')->where('continue_id',$con)->value('continue_coupon');
                if($coupon){
                    $cangive = $this->couponStatusNow($user_id,$coupon);
                    if($cangive == true){
                        $res = Db::table('up_coupon')->where('coupon_id',$coupon)->field('coupon_name,coupon_price,coupon_id,coupon_use')->find();
                        return $res;
                    }else{
                        return false;
                    }
                }
            }

        }
        return false;
    }
    /***
     * @return bool
     * 闯关获取题目时记录下此次闯关情况
     */
    protected function gameHisJilu ($user_id,$rg_id)
    {
        $data = array();
        $data['rhis_user_id'] = $user_id;
        $data['rhis_game_id'] = $rg_id;
        $data['rhis_game_id'] = $rg_id;
        $game = Db::table('up_reading_game')->where('rg_id',$rg_id)->field('rg_rb_id,rg_name')->find();
        $book = Db::table('up_reading_book')->where('rb_id',$game['rg_rb_id'])->field('rb_name')->find();
        $data['rhis_book_game'] = $book['rb_name'] . '/' .$game['rg_name'];
        $data['rhis_book_pass'] = Db::table('up_reading_book_pass')
            ->where('rbp_user_id',$user_id)->count();
        $numdata = Db::table('up_reading_game_pass')
            ->where('rgp_user_id',$user_id)
            ->field('count(*) number,sum(rgp_exp) exp,sum(rgp_score) score')
            ->find();
        $data['rhis_game_pass'] = $numdata['number'];
        $data['rhis_exp_all'] = $numdata['exp'];
        $data['rhis_score_all'] = $numdata['score'];
        $data['rhis_time'] = date('Y-m-d H:i:s');
        Db::table('up_reading_history')->insert($data);
        return true;
    }
    /***
     *
     * 完善资料后送书
     */
    protected function wanshanSendBook ($user_id)
    {
        $user = Db::table('up_u_user')->where('user_id',$user_id)->field('user_type,user_school,user_wanshan')->find();
//        ------------------------------------------------------------------------
        if($user['user_type'] == 1){
            $grade = Db::table('up_grade_class')
                ->where('gs_user_id',$user_id)
                ->value('gs_grade_id');
            $book = Db::table('up_grade')
                ->where('grade_id',$grade)
                ->value('grade_books');
            //-----------我是不是在这个年级通关过 start--------
//            $havepass = Db::table('up_reading_book_pass')->alias('bp')
//                ->join('up_reading_book b','bp.rbp_book_id=b.rb_id')
//                ->where('rbp_user_id',$user_id)
//                ->where('rb_status',1)
//                ->where('rb_grade_id',$grade)
//                ->find();
            //-----------我是不是在这个年级通关过 end--------
        }else{
            $grade = Db::table('up_grade_class')
                ->where('gs_user_id',$user_id)
                ->group('gs_grade_id')
                ->column('gs_grade_id');
            //-----------我是不是在这些个年级通关过 start--------
//            $havepass = Db::table('up_reading_book_pass')->alias('bp')
//                ->join('up_reading_book b','bp.rbp_book_id=b.rb_id')
//                ->where('rbp_user_id',$user_id)
//                ->where('rb_status',1)
//                ->where('rb_grade_id','in',$grade)
//                ->find();
            //-----------我是不是在这些个年级通关过 end--------
            $book = Db::table('up_grade')
                ->where('grade_id','in',$grade)
                ->column('grade_books');
            if($book){
                $book = implode($book,',');
            }
        }
        if($book){
            $book = explode(',',$book);
            $ids = array();
            if(count($book) > 3){
                $keys = array_rand($book,3);
                foreach ($keys as $v){
                    $ids[] = $book[$v];
                }
            }else{
                $ids = $book;
            }
            $ids = ',' . implode($ids,',') . ',';//加俩逗号
        }else{
            $ids = '';
        }
        $update = array();
        $update['user_wanshan'] = 2;
        $update['user_default_book'] = $ids;
//        $update['user_pass_one'] = 1;
//        if($havepass){
//            $update['user_pass_one'] = 2;
//        }
        Db::table('up_u_user')->where('user_id',$user_id)
            ->update($update);
//        ----------------------------------------------------------------------------
        if($user['user_wanshan'] == 1){
            //加金币
            $score = Db::table('up_sign_config')->where('id',5)->value('score');
            Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_integral',$score);
            //得金币入流转start-----
            $this->goldInOut ($user_id,$score,3,1);
            //得金币入流转end-------
            //--------------------完善大礼包start---------------------------------------------------
            $res = array();
            $books = Db::table('up_reading_book')
                ->where('rb_id','in',$ids)
                ->where('rb_status',1)
                ->field('rb_name,rb_image')
                ->select();
            $res['books'] = $books;
            $res['score'] = $score;
            return $res;
            //--------------------完善大礼包 end ---------------------------------------------------
        }else{
            return false;
        }
    }

    /***
     * @return bool
     * 金币流转：
     * glod_status：1签到 2闯关  3完善信息  4段位晋升  5购物 6勋章(成就)
     * glod_type：1收入  2支出
     */
    protected function goldInOut ($user_id,$money,$status,$type)
    {
        $data = [
            'glod_time'=>date('Y-m-d H:i:s'),
            'glod_user_id'=>$user_id,
            'glod_money'=>$money,
            'glod_status'=>$status,
            'glod_type'=>$type,
        ];
        Db::table('up_glod')->insert($data);
        return true;
    }

    /***
     *
     * 升级后加金币入流水：
     */
    protected function levelUp ($user_id,$newexp,$level_before)
    {
        $level_after = Db::table('up_exp_level')
            ->where('el_min','<=',$newexp)
            ->order('el_level DESC')
            ->find();
        $coupon_name = Db::table('up_coupon')
            ->where('coupon_id',$level_after['el_price_coupon'])
            ->field('coupon_name,coupon_price,coupon_use')->find();
        if($level_after['el_level'] > $level_before){
            $level_after['exp'] = $newexp;
            $level_after['name'] = $coupon_name['coupon_name'];
            $level_after['price'] = $coupon_name['coupon_price'];
            $level_after['coupon_use'] = $coupon_name['coupon_use'];
            //2-1、先涨金币并且改当前的level
            Db::table('up_u_user')->where('user_id',$user_id)
                ->setInc('user_integral',$level_after['el_price_score']);
            Db::table('up_u_user')->where('user_id',$user_id)->update(['user_level'=>$level_after['el_id']]);
            //2-2、再送优惠券：
            $cangive = $this->couponStatusNow($user_id,$level_after['el_price_coupon']);
            //得金币入流转start-----
            $this->goldInOut ($user_id,$level_after['el_price_score'],4,1);
            //得金币入流转end-------
            if($cangive == false){
                $level_after['price'] = '';
            }
            return $level_after;
        }else{
            return false;
        }
    }
    
    /**
     * 极光推送
     * @param $type 1:推送个人  2:推送全体
     * @param $alias 别名 user_id OR token
     * @param $message 推送消息内容
     * @param $extras 扩展字段接受数组
     * @return array
     */
    public function Jpush($type,$alias,$message,$extras)
    {
//        $alias = (string)$alias;
        import('jpush.autoload', EXTEND_PATH);
        //初始化JPushClient
        $client = new \JPush\Client(config('jpush.appKey'),config('jpush.masterSecret'));
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        //IOS推送
        $push->iosNotification($message, [
                'alert'=>$message,
                'badge' => '+1',
                'extras' => $extras,
                'sound'=>'default'
            ]
        );
        //Android推送
        $push->androidNotification($message, [
                'alert'=>$message,
                'extras' => $extras
            ]
        );
        return $push->send();
    }
    /**
     * 获取多余的超重的运费钱
     */
    public function getOverYunFei($gcid,$type)
    {
        //--------------------额外加的超重的费用 start -------------------------------------
        $biaozhun = Db::table('up_sign_config')->where('id',8)->find();
        $over = 0;
        if($type == 1){
            if($biaozhun['score'] > 0 && $biaozhun['exp'] > 0 && $biaozhun['remark'] > 0){
                $weight = Db::table('up_goods')->where('good_id',$gcid)->value('good_weight');
                if($weight > $biaozhun['score']){
                    $chazhi = ceil(($weight - $biaozhun['score'])/$biaozhun['exp']);
                    $over = $chazhi * $biaozhun['remark'];
                }
            }
        }
        if($type == 2){
            if($biaozhun['score'] > 0 && $biaozhun['exp'] > 0 && $biaozhun['remark'] > 0){
                $cars = Db::table('up_shop_car')->where('car_id','in',"$gcid")
                    ->field('car_goodid,car_number')->select();
                $allweighr = 0;
                foreach ($cars as $k=>$v){
                    $weight = Db::table('up_goods')->where('good_id',$v['car_goodid'])->value('good_weight');
                    $weights = $weight * $v['car_number'];
                    $allweighr += $weights;
                }
                if($allweighr > $biaozhun['score']){
                    $chazhi = ceil(($allweighr - $biaozhun['score'])/$biaozhun['exp']);
                    $over = $chazhi * $biaozhun['remark'];
                }
            }
        }
        return $over;
        //--------------------额外加的超重的费用 end -------------------------------------
    }
}